<?php
// +----------------------------------------------------------------------
// | 多客怪兽框架多平台开发框架 [ 以下开发工具自动生成-版权勿删 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2021~2024 http://www.dkyx.cc All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 刘泓宾（514660094@qq.com）
// +----------------------------------------------------------------------

namespace addons\cloud_market\model;

use addons\cloud_market\utils\Wechat;
use Exception;
use think\model\concern\SoftDelete;

/**
 * 订单管理模型文件
 * Create by :  刘泓宾<514660094@qq.com>
 * Copyright :  copyright (c) 多客怪兽, www.dkyx.cc
 */
class CloudMarketOrder extends CloudMarketBaseModel
{
    // 配置软删除、启用回收站
    use SoftDelete;
    protected $deleteTime = "delete_time";

    // 字段自动类型转换
    protected $type = array(
        'other' => 'json',
    );
    // 数据输出需要追加的属性
    protected $append = array(

    );

    public $error = '';
    public function __construct(array $data = [])
    {
        parent::__construct($data);
    }


    /**
     * 关联CloudMarketAddon模型
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\model\relation\BelongsTo
     */
    public function addon()
    {
        return $this->belongsTo(CloudMarketAddon::class, 'aid', 'id')->field('title,id,name,icon_image');
    }

    /**
     * 关联CloudMarketUser模型
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\model\relation\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(CloudMarketUser::class, 'user_id', 'id')->field('id,username,nickname,avatar');
    }

    /**
     * 关联CloudMarketAddonSku模型
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\model\relation\BelongsTo
     */
    public function addonSku()
    {
        return $this->belongsTo(CloudMarketAddonSku::class, 'sku_id', 'id')->field('name,service,count');
    }

    /**
     * 关联CloudMarketSite模型
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\model\relation\BelongsTo
     */
    public function site()
    {
        return $this->belongsTo(CloudMarketSite::class, 'site_id', 'id')->field('title,domain');
    }

    /**
     * 关联CloudMarketUser模型
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\model\relation\BelongsTo
     */
    public function agentUser()
    {
        return $this->belongsTo(CloudMarketUser::class, 'agent_id', 'id')->field('id,username,nickname,avatar');
    }


    /**
     * 发送应用
     * Create by :  刘泓宾<514660094@qq.com>
     * @param $out_trade_no
     * @param $transaction_id
     * @return CloudMarketOrder|array|false|\think\Model
     */
    public function sendAddon($out_trade_no, $transaction_id = '')
    {
        $order = $this->where(['out_trade_no' => $out_trade_no, 'type' => 'buy_addon'])->find();
        if ($order) {
            try {
                $DkSiteAddon = new CloudMarketSiteAddon();
                $addon = $DkSiteAddon->where(['site_id' => $order['site_id'], 'addon_id' => $order['aid']])->find();
                if ($addon) {
                    $this->error = "当前用户已经拥有了此应用";
                    return false;
                }
                $data = [
                    'site_id'     => $order['site_id'],
                    'addon_id'    => $order['aid'],
                    'count'       => 1,//授权平台数
                    'servicetime' => time() + 365 * 24 * 60 * 60 //服务期限
                ];
                $sku_id = $order['sku_id'] ?? 0;
                if ($sku_id > 0) {
                    //存在Sku
                    $sku = (new CloudMarketAddonSku())->find($sku_id);
                    $data['count'] = $sku['count'];
                    if ($sku['service'] > 0) {
                        $data['servicetime'] = time() + 24 * 60 * 60 * intval($sku['service']) * 30;
                    }
                }
                $DkSiteAddon->save($data);
                $order->transaction_id = $transaction_id;
                $order->status = 1;
                $order->save();
                return $order;
            } catch (Exception $e) {
//                Log::debug(['e' => $e->getMessage()]);
                $this->error = $e->getMessage();
                return false;
            }
        } else {
            $this->error = "订单不存在，或不符合代付款订单";
        }
        return false;
    }

    /**
     * 发送服务
     * Create by :  刘泓宾<514660094@qq.com>
     * @param $out_trade_no
     * @param $transaction_id
     * @return CloudMarketOrder|array|false|\think\Model
     */
    public function sendService($out_trade_no, $transaction_id = '')
    {
        $order = $this->where(['out_trade_no' => $out_trade_no])->find();
        if ($order) {
            try {
                $DkSiteAddon = new CloudMarketSiteAddon();
                $siteAddon = $DkSiteAddon->where(['site_id' => $order['site_id'], 'addon_id' => $order['aid']])->find();
                if ($siteAddon['servicetime'] > time()) {
                    $siteAddon->servicetime = $siteAddon['servicetime'] + 365 * 24 * 60 * 60;
                } else {
                    $siteAddon->servicetime = time() + 365 * 24 * 60 * 60;
                }
                $siteAddon->save();
                $order->transaction_id = $transaction_id;
                $order->status = 1;
                $order->save();
                return $order;
            } catch (Exception $e) {
//                Log::debug(['e' => $e->getMessage()]);
                $this->error = $e->getMessage();
                return false;
            }
        }
        return false;
    }

    /**
     * 发送激活数
     * Create by :  刘泓宾<514660094@qq.com>
     * @param $out_trade_no
     * @param $transaction_id
     * @return CloudMarketOrder|array|false|\think\Model
     */
    public function sendToken($out_trade_no, $transaction_id = '')
    {
        $order = $this->where(['out_trade_no' => $out_trade_no])->find();
        if ($order) {
            try {
                $DkSiteAddon = new CloudMarketSiteAddon();
                $siteAddon = $DkSiteAddon->where(['site_id' => $order['site_id'], 'addon_id' => $order['aid']])->find();
                $token_key = $order['other']['token_key'] ?? 0;
                $token_prices = $order['other']['token_prices'] ?? [];
                $token = $token_prices[$token_key] ?? [];
                $number = $token['number'];
                $siteAddon->count = $siteAddon['count'] + $number;
                $siteAddon->save();
                $order->transaction_id = $transaction_id;
                $order->status = 1;
                $order->save();
                return $order;
            } catch (Exception $e) {
//                Log::debug(['e' => $e->getMessage()]);
                $this->error = $e->getMessage();
                return false;
            }
        }
        return false;
    }


    /**
     * 处理订单
     * Create by :  刘泓宾<514660094@qq.com>
     * @param $out_trade_no
     * @return false
     */
    public function dealWithOrder($out_trade_no)
    {
        $total_fee = $this->where(['out_trade_no' => $out_trade_no])->value("total_fee");
        //查询订单状态
        $res = $this->checkOrderPayStatus($out_trade_no);
        if ($res || $total_fee == 0) {
            $order = $this->where(['out_trade_no' => $out_trade_no])->find();

            if ($order['type'] == 'buy_addon') {
                return $this->sendAddon($out_trade_no, $res['transaction_id'] ?? '');
            } elseif ($order['type'] == 'buy_service') {
                return $this->sendService($out_trade_no, $res['transaction_id'] ?? '');
            } elseif ($order['type'] == 'buy_token') {
                return $this->sendToken($out_trade_no, $res['transaction_id'] ?? '');
            }
            return false;
        } else {
            return false;
        }
    }

    /**
     * 检测订单支付状态
     * @param $out_trade_no
     * @return array|false
     */
    public function checkOrderPayStatus($out_trade_no)
    {
        $wechatApp = (new Wechat())->getApp();
        $res = $wechatApp->order->queryByOutTradeNumber($out_trade_no);
        if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {
            if ($res['trade_state'] == 'SUCCESS') {
                //未支付
                return $res;
            } else {
                return false;
            }
        } else {
            //其他
            return false;
        }
    }
}
